package com.dtp.core;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.ByteArrayResource;

import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author evolution
 * @title: NacosRefresher
 * @projectName dtp-nacos
 * @description: TODO
 * @date 2022-10-20 15:09
 */
@Slf4j
public class NacosListener implements Listener, InitializingBean {
    @NacosInjected
    private ConfigService configService;
    


    // 这个是Nacos收到变更事件异步执行逻辑要用到的线程池，跟动态线程池没关系
    @Override
    public Executor getExecutor() {
        return Executors.newFixedThreadPool(1);
    }

    //接收变化后的数据
    @Override
    public void receiveConfigInfo(String content) {
        try{
            YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
            bean.setResources(new ByteArrayResource(content.getBytes()));
            Properties properties = bean.getObject();
            System.out.println(properties);
            
            DtpProperties dtpProperties = new DtpProperties();
            ConfigurationPropertySource sources = new MapConfigurationPropertySource(properties);
            Binder binder = new Binder(sources);
            ResolvableType type= ResolvableType.forClass(DtpProperties.class);
            Bindable<?> target =Bindable.of(type).withExistingValue(dtpProperties);
            binder.bind("dtp",target);
            
            
            List<DtpProperties.DtpExecutorProperties> executors = dtpProperties.getExecutors();
            for(DtpProperties.DtpExecutorProperties executorProperties : executors){
                DtpExecutor dtpExecutor = DtpUtil.get(executorProperties.getName());
                dtpExecutor.setCorePoolSize(executorProperties.getCorePoolSize());
                dtpExecutor.setMaximumPoolSize(executorProperties.getMaximumPoolSize());
            }

        }catch (Exception e){
            log.error("错误信息",e);
        }
    }

     //利用Spring的Bean初始化机制，来设置要监听的nacos的dataid
    // 暂时写死，最好是拿到程序员所配置的dataid和group
    @Override
    public void afterPropertiesSet() throws Exception {
     configService.addListener("dtp.yaml","DEFAULT_GROUP",this);
    }
}
